package yxy.game.pm2.future.module;

import org.joda.time.DateTime;

import org.quartz.*;
import yxy.apple.util.concurrent.ThreadPoolManager;
import yxy.apple.util.quartz.QuartzSchedulerManager;
import yxy.game.pm2.bean.timeline.FutureRunnable;
import yxy.game.pm2.bean.timeline.JobHandle;

public class ScheduleFutureHandle {
	static private ScheduleFutureHandle instance;

	public static ScheduleFutureHandle getInstance() {
		if (instance == null) {
			instance = new ScheduleFutureHandle();
		}
		return instance;
	}

	public void register(FutureRunnable runnable) {
		register(runnable, runnable.period());// 默认一分钟一刷
	}

	public void register(FutureRunnable runnable, long period) {
		runnable.init();

		DateTime now = DateTime.now();
		long delay = period - now.getMillisOfDay() % period;
		ThreadPoolManager.getInstance().scheduleAtFixedRate(runnable, delay, period);
	}

	public void quartzRegister(JobHandle jobHandle) {
		try {
			Scheduler scheduler = QuartzSchedulerManager.getInstance().getScheduler();
			JobDetail jobDetail = JobBuilder.newJob(jobHandle.getClass()).build();

			if (jobHandle.jobType() == JobHandle.JOB_TYPE_CROND) {
				CronTrigger trigger = TriggerBuilder.newTrigger().startNow()
						.withSchedule(CronScheduleBuilder.cronSchedule(jobHandle.crond()))
						.build();
				scheduler.scheduleJob(jobDetail, trigger);
			} else {
				Trigger trigger = TriggerBuilder.newTrigger().startNow()
						.withSchedule( SimpleScheduleBuilder.simpleSchedule().withIntervalInMinutes((int) jobHandle.period()).repeatForever() )
						.build();
				scheduler.scheduleJob(jobDetail, trigger);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
